import { createElement, useEffect, useRef, useState, useMemo } from 'react';
import { DatePicker, Radio, Select, Input, InputNumber } from 'antd';
import { find } from 'lodash';
import IconFont from '@/components/IconFont';
import AreaSelect from '@/components/AreaSelect';
import { CloseCircleFilled, DoubleLeftOutlined } from '@ant-design/icons';
import { useFetch } from '@/pages/OrderModule/common/hooks/useFetch';
import SelectShopModal from '@/pages/OrderModule/common/bizcomponents/SelectShopModal';
import GoodsSelectModal from '@/pages/OrderModule/common/bizcomponents/GoodsSelectModal';
import { TagLabel } from '@/pages/OrderModule/common/bizcomponents/TagLabel';
import { SelectBatchInput } from '../components/SelectBatchInput/index1';
import ExcludeTagModal from '../components/TagModal/exclude';
import IncludeTagModal from '../components/TagModal/include';
import FieldWrapper from '../components/FieldWrapper';
import SearchAddress from '../components/OrderSn/SearchAddress';
import { SelectRangeInput } from '../components/SelectRangeInput';
import { queryShopList, queryQimenShopList } from '@/pages/OrderModule/common/bizcomponents/SelectShopModal/server';
import { queryWarehouseList, queryExpressList, queryTagList } from '@/pages/OrderModule/orderList/services.js';
import {
  qmErpSnArrOptions, wareHouseStateOptions, printStateOptions, goodsOptions, goodsOptionsSku, goodsOptionsSpu, unitPriceOptions, priceTypeOptions,
  expressStatusOptions, expressBackOptions, flagOptions, orderTypeOptions, deliveryPrintStateOptions, initFilterConfigList
} from './constant';
import { getCurrentUser } from '@/utils/authority.js';
import DynamicStoreSelectKX from '@/components/DynamicStoreSelectKX/index';

const { RangePicker } = DatePicker;
const dateFormat = "YYYY-MM-DD HH:mm:ss";

export const RenderSnArr = ({ value, onChange }) => {
  return <SelectBatchInput
    value={value}
    defaultSelectValue="snArr"
    placeholder="系统订单号，多个逗号隔开"
    onChange={v => onChange(v?.snArr)}
  />
}

export const RenderOutOrderSnArr = ({ value, onChange }) => {
  return <SelectBatchInput
    value={value}
    defaultSelectValue="outOrderSnArr"
    placeholder="店铺订单号，多个逗号隔开"
    onChange={v => onChange(v?.outOrderSnArr)}
  />
}

export const RenderQmErpSnArr = ({ value, onChange, stageParams }) => {
  return <SelectBatchInput
    value={value}
    options={qmErpSnArrOptions}
    defaultSelectValue={stageParams.current.qmErpSnArr}
    handleSelectChange={(e)=>stageParams.current.qmErpSnArr = e}
    onChange={v => onChange(v?.qmErpSnArr)}
  />
}

export const RenderLogisticsNoArr = ({ value, onChange }) => {
  return <SelectBatchInput
    value={value}
    defaultSelectValue="logisticsNoArr"
    placeholder="快递单号，多个逗号隔开"
    onChange={v => onChange(v?.logisticsNoArr)}
  />
}

export const RenderProvinceIdArr = ({ value, onChange, stageParams }) => {
  const handleChange = (areaIds, treeData) => {
    stageParams.current.areaTreeData = treeData;
    onChange(treeData);
  }
  return  <FieldWrapper label='省市区'>
     <AreaSelect handleChange={handleChange} initSelectData={stageParams.current.areaTreeData || []} />
  </FieldWrapper>
  return <FieldWrapper
    label={
      <Select
        value={stageParams.current.provinceIdArr}
        style={{ flex: '0, 0 60px' }}
        options={[
          { label: '省', value: 'provinceIdArr' },
          { label: '市', value: 'cityIdArr' },
          { label: '区', value: 'districtIdArr' },
        ]}
        dropdownMatchSelectWidth={false}
        onChange={(e) => {
          onChange([]);
          stageParams.current.provinceIdArr = e;
        }}
      ></Select>
    }
  >
    <SearchAddress
      type={stageParams.current.provinceIdArr}
      style={{ width: '180px' }}
      value={value}
      onChange={onChange}
    />
  </FieldWrapper>;
}

export const RenderBuyerAccount = ({ value, onChange }) => {
  const triggerChange = (changedValue) => {
    onChange?.({ ...value, ...changedValue });
  };

  const onInputChange = (key, value) => {
    triggerChange({ [key]: value });
  };

  return <FieldWrapper>
    <Input value={value} placeholder="请输入买家账号" allowClear
      onChange={(e) => onChange(e.target.value)} />
  </FieldWrapper>;
}

// export const RenderPhone = ({ value, onChange }) => {
//   return <SelectBatchInput
//     value={value}
//     defaultSelectValue="phone"
//     placeholder="手机号，多个逗号隔开"
//     onChange={v => onChange(v?.phone)}
//   />
// }

export const RenderPhone = ({ value, onChange }) => {
  return <FieldWrapper>
    <Input value={value} placeholder="请输入手机号" allowClear
      onChange={(e) => onChange(e.target.value)} />
  </FieldWrapper>;
}

export const RenderPayStateArr = ({ value, onChange }) => {
  const triggerChange = (changedValue) => {
    onChange?.({ ...value, ...changedValue });
  };
  return <FieldWrapper label="支付状态">
    <Select
      value={value}
      mode="multiple"
      maxTagCount={'responsive'}
      onChange={(v) => onChange(v)}
      allowClear
      placeholder="请选择"
      options={[
        {
          value: 0,
          label: '未支付',
        },
        {
          value: 1,
          label: '已支付',
        },
        {
          value: 3,
          label: '部分支付',
        },
      ]}
      clearIcon={<IconFont type="iconguanbi2fill" style={{ fontSize: '14px' }} />}
    />
  </FieldWrapper>;
}

export const RenderPrintState = ({ value, onChange }) => {
  return <FieldWrapper>
    <Select
      value={value}
      allowClear
      placeholder="快递单打印状态"
      options={printStateOptions}
      onChange={(v) => onChange(v)}
      clearIcon={<IconFont type="iconguanbi2fill" style={{ fontSize: '14px' }} />}
    />
  </FieldWrapper>;
}

export const RenderDeliveryPrintState = ({ value, onChange }) => {
    return <FieldWrapper>
      <Select
        value={value}
        allowClear
        placeholder="发货单打印状态"
        options={deliveryPrintStateOptions}
        onChange={(v) => onChange(v)}
        clearIcon={<IconFont type="iconguanbi2fill" style={{ fontSize: '14px' }} />}
      />
    </FieldWrapper>;
  }

export const RenderPrintBatch = ({ value, onChange }) => {
  return <FieldWrapper>
  <Input
    allowClear
    value={value}
    placeholder="请输入打印批次"
    allowclear="true"
    onChange={(e) => onChange(e.target.value)}
  />
</FieldWrapper>;
}

export const RenderWarehouseOrderStateArr = ({ value, onChange }) => {
  return <FieldWrapper>
    <Select
      mode="multiple"
      maxTagCount={'responsive'}
      value={value}
      allowClear
      placeholder="选择仓库状态"
      options={wareHouseStateOptions}
      onChange={(v) => onChange(v)}
      clearIcon={<IconFont type="iconguanbi2fill" style={{ fontSize: '14px' }} />}
    />
  </FieldWrapper>;
}

export const RenderEcStoreIdArr = ({ value, onChange }) => {

  const [platformShop, setPlatformShop] = useState(value?.ecStoreIdArr || []);

  const { data: platformShopResp, fetch: fetchPlatformShop } = useFetch(getShopOptions, {}, false);

  useEffect(() => {
    fetchPlatformShop();
  }, []);

  useEffect(() => {
    onChange(platformShop?.length ? platformShop : undefined);
  }, [platformShop]);

  function getShopOptions(data) {
    return queryShopList(data).then((res) => {
      return res?.data?.records.map((item) => {
        return { value: item.id, label: item.storeName };
      });
    });
  }

  return <SelectShopModal
    multiple
    defaultValue={value}
    onChange={(data) => {
      if (data) {
        setPlatformShop(data.map((item) => item.value));
        return;
      }

      setPlatformShop([]);
    }}
  >
    <Select
      open={false}
      mode="multiple"
      maxTagCount={'responsive'}
      allowClear
      placeholder="请选择平台店铺"
      className='translateXSelect'
      value={value}
      options={platformShopResp}
      onClear={(e) => {
        setPlatformShop([]);
      }}
      onDeselect={(id) => {
        const value = platformShop;
        const index = value.findIndex((item) => item === id);
        value.splice(index, 1);
        setPlatformShop(value.slice());
      }}
      clearIcon={<IconFont type="iconguanbi2fill" style={{ fontSize: '14px' }} />}
    />
  </SelectShopModal>;
}

export const RenderQmStoreIdArr = ({ value, onChange }) => {

  const [qimenShop, setQimenShop] = useState(value?.qmStoreIdArr || []);

  const { data: qimenShopResp, fetch: fetchQimenShop } = useFetch(getQimenShopOptions, {}, false);

  useEffect(() => {
    fetchQimenShop();
  }, []);

  useEffect(() => {
    onChange(qimenShop?.length ? qimenShop : undefined);
  }, [qimenShop]);

  function getQimenShopOptions(data) {
    return queryQimenShopList(data).then((res) => {
      return res?.data?.records.map((item) => {
        return { value: item.id, label: item.storeName };
      });
    });
  }

  return <SelectShopModal
    multiple
    defaultValue={value}
    modalProps={{ title: '选择奇门店铺' }}
    extraQuery={{ type: 13 }}
    onChange={(data) => {
      if (data) {
        setQimenShop(data.map((item) => item.value));
        return;
      }

      setQimenShop([]);
    }}
  >
    <Select
      open={false}
      mode="multiple"
      maxTagCount={'responsive'}
      placeholder="请选择奇门店铺"
      className='translateXSelect'
      value={value}
      options={qimenShopResp}
      allowClear
      onClear={(e) => {
        setQimenShop([]);
      }}
      onDeselect={(id) => {
        const value = qimenShop;
        const index = value.findIndex((item) => item === id);
        value.splice(index, 1);

        setQimenShop(value.slice());
      }}
      clearIcon={<IconFont type="iconguanbi2fill" style={{ fontSize: '14px' }} />}
    />
  </SelectShopModal>;
}

export const RenderWarehouseId = ({ value, onChange, handleFormLoad }) => {

  const { data: resp, fetch: fetchWareHouseList } = useFetch(queryWarehouseList, {}, false);

  const currentUuid = useMemo(() => {
    return getCurrentUser()?.uuid;
  }, [])

  useEffect(() => {
    fetchWareHouseList();
  }, []);

  const warehouseFlag = useMemo(() => {
    const wareHouseList = [], defaultIds = [], zifaIds = [];
    if (resp && resp.data?.length) {
      resp.data.map((item) => {
        const isZifa = item.uuid == currentUuid;
      
        wareHouseList.push({
          label: `${item.warehouseName} (${isZifa ? '自发' : '代发'})`,
          value: item.id,
        })
        if(item.isDefault == 0){
          defaultIds.push(item.id);
        }
        if(isZifa){
          zifaIds.push(item.id);
        }
      });
    } 
    return { wareHouseList, defaultIds, zifaIds }
  }, [resp]);

  useEffect(()=>{
    if(resp?.data?.length){
      const {  wareHouseList, ...args } = warehouseFlag;
      handleFormLoad?.(args);
    }
  }, [resp])

  return <Select
      mode='multiple'
      maxTagCount='responsive'
      onChange={onChange}
      value={value}
      placeholder="选择发货仓"
      options={warehouseFlag?.wareHouseList || []}
      allowClear
      clearIcon={<IconFont type="iconguanbi2fill" style={{ fontSize: '14px' }} />}
    />
  ;
}

export const RenderSysSkuCodeArr = ({ value, onChange }) => {
  const triggerChange = (changedValue) => {
    onChange?.({ ...value, ...changedValue });
  };
  return <FieldWrapper>
    <GoodsSelectModal
      submitCallback={(values) => {
        onChange({ sysSkuCodeArr: values.map((item) => item.skuCode) });
      }}
      getInputNumberValues={(val) => { }}
    >
      <Input value={value?.sysSkuCodeArr} placeholder="商品搜索" allowClear={{
        clearIcon: <CloseCircleFilled onClick={e => {
          e.stopPropagation();
          triggerChange({ sysSkuCodeArr: [] })
        }}
        />
      }} />
    </GoodsSelectModal>
  </FieldWrapper>;
}

export const RenderGoodsName = ({ value, onChange, stageParams }) => {
  return <FieldWrapper 
    label={
      <Select
        defaultValue={stageParams.current.goodsName} 
        options={goodsOptions} 
        onChange={(e)=> stageParams.current.goodsName = e} 
        dropdownMatchSelectWidth={false}
      />
    }
  >
    <Input
      value={value} 
      style={{ border: 0, outline: 0, boxShadow: 'none', background: 'transparent' }} 
      placeholder="请输入" 
      allowClear 
      onChange={(v) => onChange(v.target.value)} 
    />
  </FieldWrapper>
  // return <SelectBatchInput
  //   value={value}
  //   options={goodsOptions}
  //   defaultSelectValue={stageParams.current.goodsName}
  //   placeholder="请输入"
  //   allowclear="true"
  //   isBatchInput={false}
  //   onChange={(v) => onChange(v?.goodsName)}
  //   handleSelectChange={(e)=>stageParams.current.goodsName = e}
  // />;
}
export const RenderGoodsSku = ({ value, onChange, stageParams }) => {
  return <FieldWrapper 
    label={
      <Select
        defaultValue={stageParams.current.goodsSku} 
        options={goodsOptionsSku} 
        onChange={(e)=> stageParams.current.goodsSku = e} 
        dropdownMatchSelectWidth={false}
      />
    }
  >
    <Input
      value={value} 
      style={{ border: 0, outline: 0, boxShadow: 'none', background: 'transparent' }} 
      placeholder="请输入商品编码" 
      allowClear 
      onChange={(v) => onChange(v.target.value)} 
    />
  </FieldWrapper>
}
export const RenderGoodsSpu = ({ value, onChange, stageParams }) => {
  return <FieldWrapper 
    label={
      <Select
        defaultValue={stageParams.current.goodsSpu} 
        options={goodsOptionsSpu} 
        onChange={(e)=> stageParams.current.goodsSpu = e} 
        dropdownMatchSelectWidth={false}
      />
    }
  >
    <Input
      value={value} 
      style={{ border: 0, outline: 0, boxShadow: 'none', background: 'transparent' }} 
      placeholder="请输入款式编码" 
      allowClear 
      onChange={(v) => onChange(v.target.value)} 
    />
  </FieldWrapper>
}

export const RenderStoreName = ({ value, onChange, stageParams }) => {

  const supplyStoreModalProps = {
    value,
    name: 'storeIdArr',
    styles:{
      top: '2px'
    },
    initStoreList: stageParams?.current?.storeIdArr || [],
    handleAllSelect(ids, list){
      stageParams.current.storeIdArr = list;
      onChange(ids);
    }
  }

  return <DynamicStoreSelectKX {...supplyStoreModalProps} />
  return <FieldWrapper>
    <Input
      allowClear
      value={value}
      placeholder="请输入供应商名称"
      allowclear="true"
      onChange={(e) => onChange(e.target.value)}
    />
  </FieldWrapper>;
}

export const RenderStoreCode = ({ value, onChange }) => {
  return <FieldWrapper>
    <Input
      allowClear
      value={value}
      placeholder="请输入档口号"
      allowclear="true"
      onChange={(e) => onChange(e.target.value)}
    />
  </FieldWrapper>;
}

export const RenderIsMatch = ({ value, onChange }) => {
  return <FieldWrapper>
    <Select
      value={value}
      onChange={(v) => onChange(v)}
      placeholder="选择匹配状态"
      allowClear
      options={[
        {
          value: 0,
          label: '未匹配',
        },
        {
          value: 1,
          label: '已匹配',
        },
      ]}
      clearIcon={<IconFont type="iconguanbi2fill" style={{ fontSize: '14px' }} />}
    />
  </FieldWrapper>;
}

export const RenderTakeState = ({ value, onChange }) => {
  return <FieldWrapper>
    <Select
      value={value}
      onChange={(v) => onChange(v)}
      placeholder="选择备货状态"
      allowClear
      options={[
        {
          value: 0,
          label: '未备货',
        },
        {
          value: 1,
          label: '已备货',
        },
        {
          value: 2,
          label: '部分备货',
        },
      ]}
      clearIcon={<IconFont type="iconguanbi2fill" style={{ fontSize: '14px' }} />}
    />
  </FieldWrapper>;
}

export const RenderUniqueCodeArr = ({ value, onChange }) => {
  return <SelectBatchInput
    value={value}
    defaultSelectValue="uniqueCodeArr"
    placeholder="商品唯一码，多个逗号隔开"
    onChange={(v) => onChange(v?.uniqueCodeArr)}
  />;
}

export const RenderTotalGoodsNum = ({ value, onChange }) => {
  const triggerChange = (changedValue) => {
    onChange?.({ ...value, ...changedValue });
  };
  return <FieldWrapper label="货品数量">
    <div className="" style={{ display: 'flex', justifyContent: 'space-between' }}>
      <InputNumber
        value={value?.totalGoodsNumMin}
        width={36}
        controls={false}
        min={0}
        allowclear="true"
        placeholder="请输入"
        onChange={(v) => {
          triggerChange({ totalGoodsNumMin: v });
        }}
      />
      <span className="input-bettwen-line">-</span>
      <InputNumber value={value?.totalGoodsNumMax} width={36} allowclear="true" controls={false} min={0} placeholder="请输入" onChange={(v) => triggerChange({ totalGoodsNumMax: v })} />
    </div>
  </FieldWrapper>;
}

export const RenderSkuTotal = ({ value, onChange }) => {
  const triggerChange = (changedValue) => {
    onChange?.({ ...value, ...changedValue });
  };
  return <FieldWrapper label="货品种类">
    <div className="" style={{ display: 'flex', justifyContent: 'space-between' }}>
      <InputNumber allowclear="true" value={value?.skuTotalMin} width={36} controls={false} min={0} placeholder="请输入" onChange={(v) => triggerChange({ skuTotalMin: v })} />
      <span className="input-bettwen-line">-</span>
      <InputNumber allowclear="true" value={value?.skuTotalMax} width={36} controls={false} min={0} placeholder="请输入" onChange={(v) => triggerChange({ skuTotalMax: v })} />
    </div>
  </FieldWrapper>;
}

export const RenderIsSysComposeGoods = ({ value, onChange }) => {
  
  return <FieldWrapper>
    <Select
      value={value}
      onChange={(v) => onChange(v)}
      placeholder="是否有组合商品"
      allowClear
      options={[
        {
          value: 1,
          label: '是',
        },
        {
          value: 0,
          label: '否',
        },
      ]}
      clearIcon={<IconFont type="iconguanbi2fill" style={{ fontSize: '14px' }} />}
    />
  </FieldWrapper>;
}

export const RenderGoodsSate = ({ value, onChange }) => {
  
  return <FieldWrapper>
    <Select
      value={value}
      onChange={(v) => onChange(v)}
      placeholder="请选择商品状态"
      allowClear
      options={[
        {
          value: 1,
          label: '待退商品',
        },
        {
          value: 2,
          label: '已退商品',
        },
        {
          value: 3,
          label: '平台已发货',
        },
      ]}
      clearIcon={<IconFont type="iconguanbi2fill" style={{ fontSize: '14px' }} />}
    />
  </FieldWrapper>;
}

export const RenderIsSaleCode = ({ value, onChange }) => {
  
  return <FieldWrapper>
    <Select
      value={value}
      onChange={(v) => onChange(v)}
      placeholder="是否有快销码"
      allowClear
      options={[
        {
          value: 1,
          label: '是',
        },
        {
          value: 0,
          label: '否',
        },
      ]}
      clearIcon={<IconFont type="iconguanbi2fill" style={{ fontSize: '14px' }} />}
    />
  </FieldWrapper>;
}

export const RenderOrderTypeArr = ({ value, onChange, stageParams }) => {
  return <FieldWrapper>
  <Select maxTagCount={'responsive'} value={value} placeholder="订单类型" allowClear mode="multiple" options={orderTypeOptions} 
    onChange={(v) => onChange(v)}
    clearIcon={<IconFont type="iconguanbi2fill" style={{fontSize:'14px'}}/>}
    dropdownRender={(children)=>{
      return (<><div style={{display:"flex", padding: '3px 6px 0px'}}>筛选：
      <Radio.Group name='isOrderTypeOr' onChange={e=>stageParams.current.isOrderTypeOr = e.target.value} defaultValue={stageParams.current.isOrderTypeOr || false}>
        <Radio value={false}>并且</Radio>
        <Radio value={true}>或者</Radio>
      </Radio.Group>
      </div>
      {children}
     </>)
    }}
  ></Select>
</FieldWrapper>;
}

export const RenderUnitPrice = ({ value, onChange }) => {
  const triggerChange = (changedValue) => {
    onChange?.({ ...value, ...changedValue });
  };

  const handleUnitPriceChange = (v) => {
    if (v === 0.01) {
      triggerChange({ storeGoodsPrice: 0.01, isVipGoods: undefined });
    } else if (v === 1 || v === 0) {
      triggerChange({ storeGoodsPrice: undefined, isVipGoods: v });
    } else {
      triggerChange({ storeGoodsPrice: undefined, isVipGoods: undefined });
    }
  };

  return <FieldWrapper>
    <Select 
      value={value} 
      allowClear 
      placeholder="选择采购价" 
      options={unitPriceOptions} 
      onChange={(e)=>onChange(e)} 
      clearIcon={<IconFont type="iconguanbi2fill" style={{ fontSize: '14px' }} />} 
    />
  </FieldWrapper>;
}

export const RenderTotalAmount = ({ value, onChange, stageParams }) => {
  const triggerChange = (changedValue) => {
    onChange?.({ ...value, ...changedValue });
  };
  return <SelectRangeInput
    options={priceTypeOptions}
    defaultSelectValue={stageParams.current.totalAmount}
    handleChangeSelectType={e=>stageParams.current.totalAmount = e}
    value={value}
    onChange={(e) => {
      triggerChange(e);
    }}
    style={{width:"65px"}}
  ></SelectRangeInput>;
}

export const RenderWeight = ({ value, onChange }) => {
  const triggerChange = (changedValue) => {
    onChange?.({ ...value, ...changedValue });
  };
  return <FieldWrapper label="重量">
    <div style={{ display: 'flex', justifyContent: 'space-between' }}>
      <InputNumber
        value={value?.weightMin}
        width={36}
        controls={false}
        min={0}
        placeholder="请输入kg"
        onChange={(e) => {
          triggerChange({ weightMin: e });
        }}
      />
      <span className="input-bettwen-line">-</span>
      <InputNumber
        value={value?.weightMax}
        width={36}
        controls={false}
        min={0}
        placeholder="请输入kg"
        onChange={(e) => {
          triggerChange({ weightMax: e });
        }}
      />
    </div>
  </FieldWrapper>;
}

export const RenderLogisticsCompanyId = ({ value, onChange, dealSpecChange }) => {

  const { data: resp, fetch: fetchExpressList } = useFetch(queryExpressList, {}, false);

  useEffect(() => {
    fetchExpressList({ type: 1 });
  }, []);

  // 快递公司列表
  const companyList = useMemo(() => {
    if (resp && resp.data) {
      return [{ label: '无快递', value: -9999 }].concat(resp?.data?.map((item) => ({ label: item.baseExpressName, value: item.baseExpressId })));
    } else {
      return [{ label: '无快递', value: -9999 }];
    }
  }, [resp]);

  return  <FieldWrapper>
  <Select
    showSearch
    mode="multiple"
    maxTagCount='responsive'
    options={companyList}
    value={value}
    placeholder="请选择快递公司"
    optionFilterProp="label"
    allowClear
    onChange={(v) => {onChange(v); dealSpecChange('logisticsCompanyId', v)}}
    clearIcon={<IconFont type="iconguanbi2fill" style={{fontSize:'14px'}} />}
  ></Select>
</FieldWrapper>;
}

export const RenderLogisticsErrorType = ({ value, onChange }) => {
  return  <FieldWrapper>
  <Select
    value={value}
    placeholder="物流状态"
    allowClear
    options={expressStatusOptions}
    onChange={(v) => onChange(v)}
    clearIcon={<IconFont type="iconguanbi2fill" style={{fontSize:'14px'}} />}
  ></Select>
</FieldWrapper>;
}

export const RenderCallbackFlag = ({ value, onChange }) => {
  return  <FieldWrapper>
  <Select value={value} placeholder="物流回传" allowClear options={expressBackOptions} 
    onChange={(v) => onChange(v)}
    clearIcon={<IconFont type="iconguanbi2fill" style={{fontSize:'14px'}} />}
  ></Select>
</FieldWrapper>;
}

export const RenderContainLabelIdArr = ({ value, onChange }) => {

  const [includeTagModalVisible, setIncludeTagModalVisible] = useState(false);
  const [includeTagText, setIncludeTagText] = useState('');

  const isInit = useRef(true);

  useEffect(()=>{
    if(isInit.current && value){
      isInit.current = false;
      handleFillForm();
    }
  }, [value])

  const handleFillForm = async () => {
    const { data, success} = await queryTagList();
    if(success && data?.length){
      const arr = [];
      value.containLabelIdArr.map(item=>{
        const obj = find(data, ['id', item]);
        if(obj){//防止被删除
          arr.push(obj.name)
        }
      })
      setIncludeTagText(arr.join(value.isLabelOr ? ',' : '&'));
    }
  }

  const triggerChange = (changedValue) => {
    onChange?.({ ...value, ...changedValue });
  };

  const handleIncludeTagChange = (value) => {
    isInit.current = false;
    const { includeTagText: text, ...data } = value;
    setIncludeTagText(text);
    triggerChange(data);
  };

  const handleInputChange = (e) => {
    isInit.current = false;
    if(!e.target.value){
      handleIncludeTagChange({ containLabelIdArr: [] })
    }
  }

  return <FieldWrapper>
    <Input value={includeTagText} placeholder="选择包含标签" onClick={() => setIncludeTagModalVisible(true)} allowClear onChange={handleInputChange}></Input>
    <IncludeTagModal value={value} visible={includeTagModalVisible} onVisibleChange={setIncludeTagModalVisible} onChange={handleIncludeTagChange} />
  </FieldWrapper>
}

export const RenderExcludeLabelIdArr = ({ value, onChange }) => {

  const [excludeTagModalVisible, setExcludeTagModalVisible] = useState(false);
  const [excludeTagText, setExcludeTagText] = useState('');

  const isInit = useRef(true);

  useEffect(()=>{
    if(isInit.current && value){
      isInit.current = false;
      handleFillForm();
    }
  }, [value])

  const handleFillForm = async () => {
    const { data, success} = await queryTagList();
    if(success && data?.length){
      const arr = [];
      value.excludeLabelIdArr.map(item=>{
        const obj = find(data, ['id', item]);
        if(obj){//防止被删除
          arr.push(obj.name)
        }
      })
      setExcludeTagText(arr.join(','));
    }
  }

  const triggerChange = (changedValue) => {
    onChange?.({ ...value, ...changedValue });
  };

  const handleExcludeTagChange = (value) => {
    isInit.current = false;
    const { excludeTagText: text, ...data } = value;
    setExcludeTagText(text);
    triggerChange(data);
  };

  const handleInputChange = (e) => {
    isInit.current = false;
    if(!e.target.value){
      handleExcludeTagChange({ excludeLabelIdArr: [] });
    }
  }

  return <FieldWrapper>
    <Input value={excludeTagText} placeholder="选择排除标签" onClick={() => setExcludeTagModalVisible(true)} allowClear onChange={handleInputChange}></Input>
    <ExcludeTagModal value={value} visible={excludeTagModalVisible} onVisibleChange={setExcludeTagModalVisible} onChange={handleExcludeTagChange} />
  </FieldWrapper>
}

export const RenderContainFlagArr = ({ value, onChange }) => {
  return <FieldWrapper>
  <Select
    allowClear
    showArrow
    value={value}
    mode="multiple"
    maxTagCount={'responsive'}
    placeholder="选择包含旗帜"
    onChange={v => onChange(v)}
    clearIcon={<IconFont type="iconguanbi2fill" style={{fontSize:'14px'}} />}
  >
    {flagOptions.map(item => (
      <Option value={item.value} key={item.value} label={item.label}>
        <TagLabel type={'flag'} key={item.name} name={item.name}></TagLabel>
      </Option>
    ))}
  </Select>
</FieldWrapper>;
}

export const RenderExcludeFlagArr = ({ value, onChange }) => {
  return <FieldWrapper>
  <Select
    allowClear
    showArrow
    value={value}
    mode="multiple"
    maxTagCount={'responsive'}
    placeholder="选择排除旗帜"
    onChange={v => onChange(v)}
    clearIcon={<IconFont type="iconguanbi2fill" style={{fontSize:'14px'}} />}
  >
    {flagOptions.map(item => (
      <Option value={item.value} key={item.value} label={item.label}>
        <TagLabel type={'flag'} key={item.name} name={item.name}></TagLabel>
      </Option>
    ))}
  </Select>
</FieldWrapper>;
}

export const RenderEcLastDeliveryTime = ({ value, onChange }) => {
  return  <FieldWrapper>
  <Select value={value} placeholder="请选择剩余发货时间" allowClear onChange={(v) => onChange(v)} clearIcon={<IconFont type="iconguanbi2fill" style={{fontSize:'14px'}} />}>
    <Option value="1">已超时</Option>
    <Option value="2">12小时内</Option>
    <Option value="3">24小时内</Option>
    <Option value="4">3天内</Option>
  </Select>
</FieldWrapper>;
}

export const RenderellerMessage = ({ value, onChange, stageParams }) => {

  const [disabled, setDisabled] = useState(stageParams.current.sellerMessage === false);

  const handleSelectChange = (e) => {
    stageParams.current.sellerMessage = e; 
    onChange(undefined);
    if(e === 'sellerMessage') {
      setDisabled(false);
    } else {
      setDisabled(true);
    }
  }

  return <SelectBatchInput
    value={value}
    options={[{
      label: '有卖家备注',
      value: true
    },{
      label: '卖家备注',
      value: 'sellerMessage'
    },{
      label: '无卖家备注',
      value: false
    }]}
    disabled={disabled}
    isBatchInput={false}
    defaultSelectValue={stageParams.current.sellerMessage || false}
    placeholder='请输入'
    handleSelectChange={handleSelectChange}
    onChange={v => onChange(v?.sellerMessage)}
  />
}

export const RenderbuyerMessage = ({ value, onChange, stageParams }) => {

  const [disabled, setDisabled] = useState(stageParams.current.buyerMessage === false);

  const handleSelectChange = (e) => {
    stageParams.current.buyerMessage = e; 
    onChange(undefined);
    if(e === 'buyerMessage') {
      setDisabled(false);
    } else {
      setDisabled(true);
    }
  }


  return <SelectBatchInput
    value={value}
    options={[{
      label: '有买家留言',
      value: true
    },{
      label: '买家留言',
      value: 'buyerMessage'
    },{
      label: '无买家留言',
      value: false
    }]}
    disabled={disabled}
    isBatchInput={false}
    defaultSelectValue={stageParams.current.buyerMessage || false}
    placeholder='请输入'
    handleSelectChange={handleSelectChange}
    onChange={v => onChange(v?.buyerMessage)}
  />
}

export const RenderOrderRemark = ({ value, onChange, stageParams }) => {

  const [disabled, setDisabled] = useState(stageParams.current.orderRemark === false);

  const handleSelectChange = (e) => {
    stageParams.current.orderRemark = e; 
    onChange(undefined);
    if(e === 'orderRemark') {
      setDisabled(false);
    } else {
      setDisabled(true);
    }
  }

  return <SelectBatchInput
    value={value}
    options={[{
      label: '有订单备注',
      value: true
    },{
      label: '订单备注',
      value: 'orderRemark'
    },{
      label: '无订单备注',
      value: false
    }]}
    disabled={disabled}
    isBatchInput={false}
    defaultSelectValue={stageParams.current.orderRemark || false}
    placeholder='请输入'
    handleSelectChange={handleSelectChange}
    onChange={v => onChange(v?.orderRemark)}
  />
}

export const RenderTime = ({ value, onChange, stageParams }) => {
  return <FieldWrapper
    label={<Select defaultValue={stageParams.current.timeType} onChange={e=>stageParams.current.timeType = e} style={{width:"108px"}}>
    <Option value="ecPayTime">平台付款时间</Option>
    <Option value="checkTime">订单审核时间</Option>
    <Option value="deliveryTime">订单发货时间</Option>
  </Select>}
  >
    <RangePicker value={value} format={dateFormat} showTime onChange={v => onChange(v)} />
  </FieldWrapper>;
}

export default {
  'phone': RenderPhone,
  'snArr': RenderSnArr,
  'outOrderSnArr': RenderOutOrderSnArr,
  'containLabelIdArr': RenderContainLabelIdArr,
  'excludeLabelIdArr': RenderExcludeLabelIdArr,
  'qmErpSnArr': RenderQmErpSnArr,
  'shippingNotePrintState': RenderDeliveryPrintState,
  'logisticsNoArr': RenderLogisticsNoArr,
  'provinceIdArr': RenderProvinceIdArr,
  'buyerAccount': RenderBuyerAccount,
  'payStateArr': RenderPayStateArr,
  'warehouseOrderStateArr': RenderWarehouseOrderStateArr,
  'printState': RenderPrintState,
  'printBatch': RenderPrintBatch,
  'ecStoreIdArr': RenderEcStoreIdArr,
  'qmStoreIdArr': RenderQmStoreIdArr,
  'warehouseIdArr': RenderWarehouseId,
  'sysSkuCodeArr': RenderSysSkuCodeArr,
  'goodsName': RenderGoodsName,
  'goodsSku': RenderGoodsSku,
  'goodsSpu': RenderGoodsSpu,
  'storeIdArr': RenderStoreName,
  'storeCode': RenderStoreCode,
  'isMatch': RenderIsMatch,
  'takeState': RenderTakeState,
  'uniqueCodeArr': RenderUniqueCodeArr,
  'totalGoodsNum': RenderTotalGoodsNum,
  'skuTotal': RenderSkuTotal,
  'isSysComposeGoods': RenderIsSysComposeGoods,
  'goodsSate': RenderGoodsSate,
  'isSaleCode': RenderIsSaleCode,
  'orderTypeArr': RenderOrderTypeArr,
  'unitPrice': RenderUnitPrice,
  'totalAmount': RenderTotalAmount,
  'weight': RenderWeight,
  'logisticsCompanyId': RenderLogisticsCompanyId,
  'logisticsErrorType': RenderLogisticsErrorType,
  'callbackFlag': RenderCallbackFlag,
  'containFlagArr': RenderContainFlagArr,
  'excludeFlagArr': RenderExcludeFlagArr,
  'sellerMessage': RenderellerMessage,
  'buyerMessage': RenderbuyerMessage,
  'orderRemark': RenderOrderRemark,
  'time': RenderTime,
  'ecLastDeliveryTime': RenderEcLastDeliveryTime
}

/**
 * 
 * @param {string} str 
 * @returns 
 */
const formatComponentName = (str) => {
  if (!str) return null;
  return 'Render' + str.replace(str.charAt(0), str.charAt(0).toUpperCase());
}

// export default initFilterConfigList.map(item=>{
//   return {
//     ...item,
//     Component: formatComponentName(item.name)
//   }
// })